package com.dd.cloud.common.config.weather;

import com.alibaba.fastjson.JSON;
import com.dd.cloud.common.utils.HttpRequestUtils;
import com.dd.cloud.common.vo.WeatherInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Lx
 * @version 1.0
 * @date 2023/10/8
 */
@Slf4j
@Component
public class WeatherUtils {
    @Autowired
    private WeatherProperties weatherProperties;
    /**
     * 缓存key值
     */
    public static final String KEY = "weather-redis-key-";
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询天气信息
     *
     * @param province
     * @param city
     * @param ip
     * @return
     */
    public WeatherInfoVo getWeatherInfo(String province, String city, String ip) {
        String addressUrl = String.format(weatherProperties.getUrl(), weatherProperties.getAppid(), weatherProperties.getAppsecret());
        try {
            if (StringUtils.isNotBlank(city)) {
                if (StringUtils.isNotBlank(province)) {
                    addressUrl += "&province=" + province;
                }
                addressUrl += "&city=" + city;
            } else if (StringUtils.isNotBlank(ip)) {
                addressUrl += "&ip=" + ip;
            }
            WeatherInfoVo vo = getWeatherRedis(KEY + addressUrl);
            if (vo != null) {
                return vo;
            }
            String res = HttpRequestUtils.get(addressUrl);
            setWeatherRedis(KEY + addressUrl, res);
            return JSON.parseObject(res, WeatherInfoVo.class);
        } catch (IOException e) {
            e.printStackTrace();
            addressUrl = addressUrl.replace(weatherProperties.getUrl(), weatherProperties.getUrls());
            WeatherInfoVo vo = getWeatherRedis(KEY + addressUrl);
            if (vo != null) {
                return vo;
            }
            try {
                String res = HttpRequestUtils.get(addressUrl);
                setWeatherRedis(KEY + addressUrl, res);
                return JSON.parseObject(res, WeatherInfoVo.class);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return new WeatherInfoVo();
    }

    /**
     * 设置缓存数据
     *
     * @param key
     * @param value
     */
    public void setWeatherRedis(String key, String value) {
        redisTemplate.opsForValue().set(key, value, 5, TimeUnit.MINUTES);
    }

    /**
     * 获取缓存数据
     *
     * @param key
     * @return
     */
    public WeatherInfoVo getWeatherRedis(String key) {
        String value = redisTemplate.opsForValue().get(key);
        return JSON.parseObject(value, WeatherInfoVo.class);
    }
}
